package com.itheima.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    //私有构造方法
    private MyBatisUtils() {
    }
    //声明工厂对象
    private static SqlSessionFactory sqlSessionFactory;
    //提供静态代码块,读取核心配置文件,并给工厂对象赋值
    static {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }
    //提供静态方法,获取SqlSession对象
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }
}
